<?php
require '../common.php';

if (!Pants::auth()) {
  header('Location: '.SITE_URL);
  exit;
}

define('PANTS_ADMIN', true);

$location = explode('/', Pants::getResponse('location', '/index'), 16);

// The first element is always empty due to the leading slash.
array_shift($location); 

switch($page = array_shift($location)) {
  // -- Article ----------------------------------------------------------------
  case 'article':
    $action  = Pants::getResponse('action');
    $article = PantsArticle::createFromResponse();

    if ($action == 'Post') {
      if ($article && $article->save()) {
        header('Location: '.SITE_URL.'/article/'.$article->id);
        exit;
      }
      else {
        Pants::error('Error', 'There was an error saving the article.');
      }
    }
  
    Pants::render('admin/article', array(
      'article'   => $article,
      'mode'      => PANTS_COMPACT,
      'pageTitle' => $article->id ? 'Edit Article' : 'Post Article',
      'preview'   => $action == 'Preview',
    ));
    break;

  // -- Page -------------------------------------------------------------------
  case 'page':
    $action = Pants::getResponse('action');
    $page   = PantsPage::createFromResponse();

    if ($action == 'Post') {
      if ($page && $page->save()) {
        header('Location: '.SITE_URL.'/page/'.$page->name);
        exit;
      }
      else {
        Pants::error('Error', 'There was an error saving the page.');
      }
    }

    Pants::render('admin/page', array(
      'mode'      => PANTS_FULL,
      'page'      => $page,
      'pageTitle' => $page->id ? 'Edit Page' : 'Create Page',
      'preview'   => $action == 'Preview',
    ));
    break;

  default:
    Pants::error404();
}
?>